<?php

namespace App\Services\Incoming;


use App\Api\Controllers\Basequery\StorePayWaysController;
use App\Api\Controllers\Config\VbillConfigController;
use App\Models\IncomingQrs;
use App\Models\Merchant;
use App\Models\ProvinceCity;
use App\Models\Store;
use App\Models\StoreBank;
use App\Models\StoreImg;
use App\Models\StorePayWay;
use App\Models\User;
use App\Models\UserRate;
use App\Models\UserStoreSet;
use App\Models\VbillStore;
use App\Models\VbillStoreCategory;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Validator;

class IncomingService
{
    public function validator(array $data): array
    {
        $validator = Validator::make($data, [
            "hkrt_bus_scope_code" => ["nullable"],
            "reserved_mobile" => ["nullable"],
            "user_id" => ["required"],
            "people_phone" => ["required"],
            "store_email" => ["nullable"],
            "head_name" => ["nullable"],
            "head_sfz_no" => ["nullable"],
            "bank_sfz_no" => ["nullable"],
            "people" => ["required"],
            "head_sfz_img_a" => ["nullable"],
            "head_sfz_img_b" => ["nullable"],
            "head_sfz_time" => ["nullable"],
            "head_sfz_stime" => ["nullable"],
            //门店信息
            "store_name" => ["required"],
            "store_short_name" => ["nullable"],
            "province_code" => ["required"],
            "city_code" => ["required"],
            "area_code" => ["required"],
            "store_address" => ["required"],
            "store_type" => ["required"],
            "store_type_name" => ["required"],
            "DLB_micro_biz_type" => ["nullable"],
            "DLB_industry" => ["nullable"],
            "DLB_second_industry" => ["nullable"],
            "DLB_province" => ["nullable"],
            "DLB_city" => ["nullable"],
            "DLB_bank" => ["nullable"],
            "DLB_sub_bank" => ["nullable"],
            "DLB_pay_bank_list" => ["nullable"],

            "longitude" => ["nullable"],
            "latitude" => ["nullable"],

            "category_id" => ["required"],
            "category_name" => ["nullable"],
            "store_logo_img" => ["nullable"],
            "store_img_a" => ["nullable"],
            "store_img_b" => ["nullable"],
            "store_img_c" => ["nullable"],
            "weixin_name" => ["nullable"],
            "weixin_no" => ["nullable"],
            "alipay_name" => ["nullable"],
            "alipay_account" => ["nullable"],

            //收款信息
            "store_alipay_account" => ["nullable"],
            "store_bank_no" => ["nullable"],
            "store_bank_phone" => ["nullable"],
            "store_bank_name" => ["nullable"],
            "store_bank_type" => ["nullable"],
            "bank_name" => ["nullable"],
            "bank_no" => ["nullable"],
            "sub_bank_name" => ["nullable"],
            "bank_province_code" => ["nullable"],
            "bank_city_code" => ["nullable"],
            "bank_area_code" => ["nullable"],
            "bank_img_a" => ["nullable"],
            "bank_img_b" => ["nullable"],
            "bank_sfz_img_a" => ["nullable"],
            "bank_sfz_img_b" => ["nullable"],
            "bank_sc_img" => ["nullable"],
            "store_auth_bank_img" => ["nullable"],
            "bank_sfz_time" => ["nullable"],
            "bank_sfz_stime" => ["nullable"],
            "store_license_no" => ["nullable"],
            "store_license_time" => ["nullable"],
            "store_license_stime" => ["nullable"],
            "head_sc_img" => ["nullable"],
            "head_store_img" => ["nullable"],
            "store_license_img" => ["nullable"],
            "store_industrylicense_img" => ["nullable"],
            "store_other_img_a" => ["nullable"],
            "store_other_img_b" => ["nullable"],
            "store_other_img_c" => ["nullable"],
            "DLB_settler_hold_settlecard" => ["nullable"],
        ], [], [
//            "hkrt_bus_scope_code" => "经营范围",
//            "reserved_mobile" => "预留手机号",
        ]);


        if ($validator->fails()) {
            throw new \Exception($validator->errors()->first());
        }
        if (empty($data["store_id"])) {
            $data["store_id"] = date('Ymdhis', time()) . rand(1000, 9999);//随机
        }
        $data["head_sfz_time"] = $this->time($data["head_sfz_time"]);
        $data["head_sfz_stime"] = $this->time($data["head_sfz_stime"]);

        if (!empty($data["dlb_pay_bank_list"])) {
            $data["dlb_pay_bank_list"] = json_encode($data["dlb_pay_bank_list"]);
        }

        $data["bank_sfz_time"] = $this->time($data["bank_sfz_time"]);
        $data["bank_sfz_stime"] = $this->time($data["bank_sfz_stime"]);
        if (empty($data["people"])) {
            $data["people"] = $data["head_name"];
        }
        if (empty($data["store_short_name"])) {
            $data["store_short_name"] = $data["store_name"];
        }

        return $data;

    }


    public function configure_channel(string $store_id)
    {
        $configure_channel_company = "vbill";//$request->get('configure_channel_company', '');
        $model = 3;//$request->get('model', ''); // 选择模式: 1: 服务费模式, 2: 代扣模式, 3: 通道扣费, 4: 预充模式


        $channel_radio = 1;//$request->get('channel_radio', '');
        $configure_channel_fee = 0.3;//$request->get('configure_channel_fee', '');

        if ($channel_radio == 1) {
            $data = [
                'store_id' => $store_id,
                'model' => $model,
                'company' => $configure_channel_company,
                'users_rate' => "",
                'channel_radio' => $channel_radio,
                'configure_channel_fee' => $configure_channel_fee,
                'money_level1' => 0,
                'money_level2' => 0,
                'money_level3' => 0,
                'create_time' => time(),
                'update_time' => time(),
            ];

        }
        if ($model == 3) {
            $all_pay_ways = DB::table('store_ways_desc')->where('company', $configure_channel_company)->get();
            $ways = DB::table('store_pay_ways')->where('store_id', $store_id)->where('company', $configure_channel_company)->first();
            if (!empty($ways)) {
                DB::table('store_pay_ways')->where('store_id', $store_id)
                    ->where('company', $configure_channel_company)
                    ->update([
                        'rate' => $configure_channel_fee,
                        "rate_a" => 0.6,
                        "rate_c" => 0.6,
                        "rate_e" => 0.6,
                        "rate_f" => 0.6,
                        "rate_f_top" => 20,
                    ]);
            } else {
                foreach ($all_pay_ways as $k => $v) {
                    $gets = DB::table('store_pay_ways')->where('store_id', $store_id)->where('ways_source', $v->ways_source)->get();
                    $count = count($gets);
                    $data1 = [
                        'store_id' => $store_id,
                        'ways_type' => $v->ways_type,
                        'company' => $v->company,
                        'ways_source' => $v->ways_source,
                        'ways_desc' => $v->ways_desc,
                        'sort' => ($count + 1),
                        'rate' => $configure_channel_fee,
                        'settlement_type' => $v->settlement_type,
                        'status' => 3,
                        'status_desc' => '未开通',
                    ];
                    DB::table('store_pay_ways')->insert($data1);
                }
            }
        }
        $configure_channel = DB::table('company_config')->where(['store_id' => $store_id, 'company' => $configure_channel_company])->first(); // 查找记录
        if ($configure_channel) {
            unset($data['create_time']);
            $data['update_time'] = time();
            DB::table('company_config')->where(['id' => $configure_channel->id])->update($data);
        } else {
            DB::table('company_config')->insert($data);
        }
    }

    public function openways(array $data)
    {
        try {
            $phone = '';
            $email = '';
            $code = $data["code"] ?? "888888";//$request->get('code', '888888');
            $store_id = $data["store_id"];//$request->get('store_id');
            $SettleModeType = "01";// $request->get('settle_mode_type', ''); //
            $qd = isset($qd) ? $qd : "1";

            $company_config = DB::table('company_config')->where(['store_id' => $store_id, 'company' => "vbill"])->first(); //查询通道
            if (empty($company_config)) {
                throw new \Exception("请先配置通道");
            }
            $store = Store::query()->where('store_id', $store_id)->first();
            if (empty($store)) {
                throw new \Exception("店铺不存在");
            }
            if ($store->people_phone) {
                $phone = $store->people_phone;
            } else {
                $merchant = Merchant::where('id', $store->merchant_id)
                    ->select('phone')
                    ->first();
                if ($merchant) {
                    $phone = $merchant->phone;
                }
            }

            return $this->base_open_ways($code, $store, $SettleModeType, $phone, $email, '', $qd);
        } catch (\Exception $ex) {
            return json_encode([
                'status' => '2',
                'message' => $ex->getMessage() . ' | ' . $ex->getFile() . ' | ' . $ex->getLine(),
            ]);
        }
    }


    //快钱组装图片
    public function images_get($img_url)
    {
        $img_url = explode('/', $img_url);
        $img_url = end($img_url);
        $img = public_path() . '/upload/images/' . $img_url;
        if ($img) {
            try {
                //压缩图片
                $img_obj = \Intervention\Image\Facades\Image::make($img);
                $img_obj->resize(800, 700);
                $img = public_path() . '/upload/s_images/' . $img_url;
                $img_obj->save($img);
            } catch (\Exception $exception) {

            }
        }

        return $img;
    }


    public function base_open_ways($store, $phone = '', $email = '')
    {
        try {
            $storePayWaysController = new StorePayWaysController();
            $myBankCategory = VbillStoreCategory::where('id', $store->category_id)
                ->first();
            if (empty($myBankCategory)) {
                throw new \Exception("随行付栏目不存在");
            }
            $storeBank = StoreBank::where('store_id', $store->store_id)->first();
            if (empty($storeBank)) {
                throw new \Exception("没有绑定银行卡,请先绑定银行卡");
            }
            $storeImg = StoreImg::where('store_id', $store->store_id)->first();

            if (empty($storeImg)) {
                throw new \Exception("没有商户资料");
            }

            $user = User::where('id', $store->user_id)
                ->select('is_delete')
                ->first();
            if (empty($user) || !empty($user->is_delete)) {
                throw new \Exception("业务员被删除无法添加门店1");
            }

            // //检测必要参数
            // $store_banks = [
            //     'store_bank_no' => $StoreBank->store_bank_no,
            //     'store_bank_name' => $StoreBank->store_bank_name,
            //     'bank_no' => $StoreBank->bank_no,
            // ];
            // $check_data = [
            //     'store_bank_no' => '银行卡号',
            //     'store_bank_name' => '持卡人名称',
            //     'bank_no' => '联行号',
            // ];
            // $check = $this->check_required($store_banks, $check_data);
            // if ($check) {
            //     return json_encode([
            //         'status' => 2,
            //         'message' => $check
            //     ]);
            // }
            $userStoreSet = UserStoreSet::where('user_id', $store->user_id)->first();
            //需要服务商审核
            if ($userStoreSet && $userStoreSet->status_check == 1 && $store->status != 1) {
                $message = "服务商未审核商户";
                if ($store->status == 3) {
                    $message = '审核失败：' . $store->status_desc;
                }
                throw new \Exception($message);
            }
            //需要平台审核
            if ($userStoreSet && $userStoreSet->admin_status_check == 1 && $store->admin_status != 1) {
                $message = "平台未审核商户";
                if ($store->status == 3) {
                    $message = '审核失败：' . $store->admin_status_desc;
                }
                throw new \Exception($message);
            }

            //公共判断
            $store_type = $store->store_type; //经营性质 1-个体工商户，2-企业，3-小微商户
            $config_id = $store->config_id;
            $store_name = $store->store_name;
            $store_short_name = $store->store_short_name;
            $store_bank_type = $storeBank->store_bank_type ? $storeBank->store_bank_type : '01'; //01 对私人 02 对公
            $store_pid = $store->pid;
            $license_no = $store->store_license_no; //营业执照号
            $store_email = $store->store_email ? $store->store_email : $email;
            $phone = $store->people_phone ? $store->people_phone : $phone;

            //查找是否有此通道
            $ways = StorePayWay::query()
                ->select(["rate", "rate_a", "rate_c", "rate_e", "rate_f", "rate_f_top", "status"])
                ->where('store_id', $store->store_id)
                ->groupBy(["rate", "rate_a", "rate_c", "rate_e", "rate_f", "rate_f_top", "status"])
                ->first();
            if (empty($ways)) {
                throw new \Exception("通道不存在");
            }
            $rate = $ways->rate; //如果门店设置走门店扫码费率
            $rate_a = $ways->rate_a;
            $rate_c = $ways->rate_c;
            if (in_array($ways->status, [1, 2])) {
                throw new \Exception("通道已经申请,不需要重复申请");
            }
            //没有邮箱 随机一个
            if ($store_email == "") {
                $store_email = '' . $phone . '@139.com';
            }


            try {
                //随行付
                $obj = new \App\Api\Controllers\Vbill\BaseController();
                $config = new VbillConfigController();
                $vbill_config = $config->vbill_config($config_id);
                if (empty($vbill_config)) {
                    throw new \Exception("随行付配置不存在请检查配置");
                }

                $privateKey = $vbill_config->privateKey;
                $sxfpublic = $vbill_config->sxfpublic;
                $orgId = $vbill_config->orgId;
                $upload_request_url = $obj->upload_url;

                //默认失败
                $send_ways_data['rate'] = $rate;
                $send_ways_data['store_id'] = $store->store_id;
                $send_ways_data['status'] = 3;
                $send_ways_data['company'] = 'vbill';
                //商户资料
                $CertPhotoA = $storePayWaysController->images_get($storeImg->head_sfz_img_a); //法人身份证正面
                $CertPhotoB = $storePayWaysController->images_get($storeImg->head_sfz_img_b); //法人身份证反面
                $ShopPhoto = $storePayWaysController->images_get($storeImg->store_logo_img); //门头照片
                $LicensePhoto = $storePayWaysController->images_get($storeImg->store_license_img); //营业执照
                $CheckstandPhoto = $storePayWaysController->images_get($storeImg->store_img_a); //收银台
                $ShopEntrancePhoto = $storePayWaysController->images_get($storeImg->store_img_b); //门店内景
                $CertPhotoA = $storePayWaysController->vbill_uploadIMG($upload_request_url, '02', $CertPhotoA, $config_id, '法人身份证正面');
                if ($CertPhotoA['status'] == 0) {
                    $send_ways_data['status_desc'] = $CertPhotoA['message'];
                    $return = $storePayWaysController->send_ways_data($send_ways_data);
                    return $return;
                }

                $CertPhotoB = $storePayWaysController->vbill_uploadIMG($upload_request_url, '03', $CertPhotoB, $config_id, '法人身份证反面');
                if ($CertPhotoB['status'] == 0) {
                    $send_ways_data['status_desc'] = $CertPhotoB['message'];
                    $return = $storePayWaysController->send_ways_data($send_ways_data);
                    return $return;
                }

                $ShopPhoto = $storePayWaysController->vbill_uploadIMG($upload_request_url, '10', $ShopPhoto, $config_id, '门头照片');
                if ($ShopPhoto['status'] == 0) {
                    $send_ways_data['status_desc'] = $ShopPhoto['message'];
                    $return = $storePayWaysController->send_ways_data($send_ways_data);
                    return $return;
                }

                $CheckstandPhoto = $storePayWaysController->vbill_uploadIMG($upload_request_url, '12', $CheckstandPhoto, $config_id, '收银台');
                if ($CheckstandPhoto['status'] == 0) {
                    $send_ways_data['status_desc'] = $CheckstandPhoto['message'];
                    $return = $storePayWaysController->send_ways_data($send_ways_data);
                    return $return;
                }

                $ShopEntrancePhoto = $storePayWaysController->vbill_uploadIMG($upload_request_url, '11', $ShopEntrancePhoto, $config_id, '内景照片');
                if ($ShopEntrancePhoto['status'] == 0) {
                    $send_ways_data['status_desc'] = $ShopEntrancePhoto['message'];
                    $return = $storePayWaysController->send_ways_data($send_ways_data);
                    return $return;
                }

                $reqData = [
                    'mecDisNm' => $store_short_name,//
                    'mblNo' => $store->people_phone,
                    'operationalType' => '01',//取值范围：01 线下 02 线上 03 非盈利类 04缴费类 05 保险类 06 私立院校
                    'mecTypeFlag' => '00',
                    'qrcodeList' => [
                        [
                            'rateType' => '01',
                            'rate' => $rate,
                        ],
                        [
                            'rateType' => '02',
                            'rate' => $rate,
                        ],
                        [
                            'rateType' => '06', //银联单笔小于等于 1000
                            'rate' => $rate_a,
                        ],
                        [
                            'rateType' => '07', //银联单笔大于 1000
                            'rate' => $rate_c,
                        ]
                    ],
                    'settleType' => '04',
                    'cprRegAddr' => $store->store_address,
                    'regProvCd' => $store->province_code . '000000',
                    'regCityCd' => $store->city_code . '000000',
                    'regDistCd' => $store->area_code . '000000',
                    'mccCd' => $myBankCategory->mcc,//类目
                    'csTelNo' => $store->people_phone,
                    'identityName' => $store->head_name,
                    'identityTyp' => '00',
                    'identityNo' => $store->head_sfz_no,
                    'legalPersonLicStt' => $store->head_sfz_stime ? date('Ymd', strtotime($store->head_sfz_stime)) : "",
                    'legalPersonLicEnt' => ($store->head_sfz_time == '长期') ? '29991231' : date('Ymd', strtotime($store->head_sfz_time)),
                    'actNm' => $storeBank->store_bank_name,
                    'actTyp' => $storeBank->store_bank_type == "02" ? "00" : "01",//00 对公 01 对私
                    'actNo' => $storeBank->store_bank_no,
                    'lbnkNo' => $storeBank->bank_no,
                    'lbnkNm' => $storeBank->sub_bank_name,
                    'legalPersonidPositivePic' => $CertPhotoA['PhotoUrl'],
                    'legalPersonidOppositePic' => $CertPhotoB['PhotoUrl'],
                    'storePic' => $ShopPhoto['PhotoUrl'],
                    'insideScenePic' => $ShopEntrancePhoto['PhotoUrl'],
                ];

                if (strpos($store->area_name, '镇')) {
                    $reqData['regDistCd'] = $store->area_code . '000';
                }

                $reqData_img = [
                    'legalPersonidPositivePic' => $CertPhotoA['PhotoUrl'],
                    'legalPersonidOppositePic' => $CertPhotoB['PhotoUrl'],
                    'storePic' => $ShopPhoto['PhotoUrl'],
                    'insideScenePic' => $ShopEntrancePhoto['PhotoUrl'],
                ];

                //非法人结算
                if ($storeBank->store_bank_type == "01" && $store->head_name != $storeBank->store_bank_name) {
                    $settlePersonIdcardPositive = $this->images_get($storeImg->bank_sfz_img_a);
                    $settlePersonIdcardOpposite = $this->images_get($storeImg->bank_sfz_img_b);
                    $letterOfAuthPic = $this->images_get($storeImg->store_auth_bank_img);

                    $settlePersonIdcardPositive = $storePayWaysController->vbill_uploadIMG($upload_request_url, '08', $settlePersonIdcardPositive, $config_id, '结算人身份证正面（人像面）');
                    if ($settlePersonIdcardPositive['status'] == 0) {
                        $send_ways_data['status_desc'] = $settlePersonIdcardPositive['message'];
                        $return = $storePayWaysController->send_ways_data($send_ways_data);
                        return $return;
                    }

                    $settlePersonIdcardOpposite = $storePayWaysController->vbill_uploadIMG($upload_request_url, '07', $settlePersonIdcardOpposite, $config_id, '结算人身份证反面（国徽面）');
                    if ($settlePersonIdcardOpposite['status'] == 0) {
                        $send_ways_data['status_desc'] = $settlePersonIdcardOpposite['message'];
                        $return = $storePayWaysController->send_ways_data($send_ways_data);
                        return $return;
                    }

                    $letterOfAuthPic = $storePayWaysController->vbill_uploadIMG($upload_request_url, '26', $letterOfAuthPic, $config_id, '非法人结算授权函');
                    if ($letterOfAuthPic['status'] == 0) {
                        $send_ways_data['status_desc'] = $letterOfAuthPic['message'];
                        $return = $storePayWaysController->send_ways_data($send_ways_data);
                        return $return;
                    }

                    $reqData['settlePersonIdcardPositive'] = $settlePersonIdcardPositive['PhotoUrl'];
                    $reqData['settlePersonIdcardOpposite'] = $settlePersonIdcardOpposite['PhotoUrl'];
                    $reqData['letterOfAuthPic'] = $letterOfAuthPic['PhotoUrl'];

                    $reqData_img['settlePersonIdcardPositive'] = $settlePersonIdcardPositive['PhotoUrl'];
                    $reqData_img['settlePersonIdcardOpposite'] = $settlePersonIdcardOpposite['PhotoUrl'];
                    $reqData_img['letterOfAuthPic'] = $letterOfAuthPic['PhotoUrl'];
                }

                //对私结算
                if ($storeBank->store_bank_type == "01") {
                    if ($store_type == 3) {
                        $reqData['stmManIdNo'] = $store->head_sfz_no;
                    } else {
                        $reqData['stmManIdNo'] = $storeBank->bank_sfz_no != "" && $storeBank->bank_sfz_no != "undefined" ? $storeBank->bank_sfz_no : $store->head_sfz_no;
                    }

                    $reqData['accountLicStt'] = $store->bank_sfz_stime ? date('Ymd', strtotime($store->bank_sfz_stime)) : date('Ymd', strtotime($store->head_sfz_stime));
                    $reqData['accountLicEnt'] = $store->head_sfz_time == '长期' ? '29991231' : date('Ymd', strtotime($store->head_sfz_time));

                    $bankCardPositivePic = $storePayWaysController->images_get($storeImg->bank_img_a); //收银台
                    $bankCardOppositePic = $storePayWaysController->images_get($storeImg->bank_img_b); //门店内景

                    $bankCardPositivePic = $storePayWaysController->vbill_uploadIMG($upload_request_url, '05', $bankCardPositivePic, $config_id, '银行卡正面');
                    if ($bankCardPositivePic['status'] == 0) {
                        $send_ways_data['status_desc'] = $bankCardPositivePic['message'];
                        $return = $storePayWaysController->send_ways_data($send_ways_data);
                        return $return;
                    }

                    $bankCardOppositePic = $storePayWaysController->vbill_uploadIMG($upload_request_url, '06', $bankCardOppositePic, $config_id, '银行卡反面');
                    if ($bankCardOppositePic['status'] == 0) {
                        $send_ways_data['status_desc'] = $bankCardOppositePic['message'];
                        $return = $storePayWaysController->send_ways_data($send_ways_data);
                        return $return;
                    }

                    $reqData['bankCardPositivePic'] = $bankCardPositivePic['PhotoUrl'];
                    $reqData['bankCardOppositePic'] = $bankCardOppositePic['PhotoUrl'];
                    $reqData_img['bankCardPositivePic'] = $bankCardPositivePic['PhotoUrl'];
                    $reqData_img['bankCardOppositePic'] = $bankCardOppositePic['PhotoUrl'];
                } else {
                    //对公结算

                    //开户许可证
                    $IndustryLicensePhoto = $storePayWaysController->images_get($storeImg->store_industrylicense_img);
                    $IndustryLicensePhoto = $storePayWaysController->vbill_uploadIMG($upload_request_url, '04', $IndustryLicensePhoto, $config_id, '开户许可证');
                    if ($IndustryLicensePhoto['status'] == 0) {
                        $send_ways_data['status_desc'] = $IndustryLicensePhoto['message'];
                        $return = $storePayWaysController->send_ways_data($send_ways_data);
                        return $return;
                    }
                    //开户许可证
                    $reqData['openingAccountLicensePic'] = $IndustryLicensePhoto['PhotoUrl'];
                    $reqData_img['openingAccountLicensePic'] = $IndustryLicensePhoto['PhotoUrl'];
                }

                //个人
                $haveLicenseNo = "01";
                $reqData['haveLicenseNo'] = $haveLicenseNo; //01 自然人 02 个体户 03 企业

                //企业
                if ($store_type == 2) {
                    $reqData['haveLicenseNo'] = "03";
                    $reqData['cprRegNmCn'] = $store_name;
                    $reqData['registCode'] = $store->store_license_no;
                    $reqData['licenseMatch'] = '00';
                    $reqData['businessLicStt'] = $store->store_license_stime ? date('Ymd', strtotime($store->store_license_stime)) : "";
                    $reqData['businessLicEnt'] = ($store->store_license_time == '长期') ? '29991231' : date('Ymd', strtotime($store->store_license_time));

                    //资料
                    $LicensePhoto = $storePayWaysController->vbill_uploadIMG($upload_request_url, '13', $LicensePhoto, $config_id, '营业执照照片');
                    if ($LicensePhoto['status'] == 0) {
                        $send_ways_data['status_desc'] = $LicensePhoto['message'];
                        $return = $storePayWaysController->send_ways_data($send_ways_data);
                        return $return;
                    }
                    //营业执照
                    $reqData['licensePic'] = $LicensePhoto['PhotoUrl'];
                    $reqData_img['licensePic'] = $LicensePhoto['PhotoUrl'];
                }

                //个体
                if ($store_type == 1) {
                    $reqData['haveLicenseNo'] = "02";
                    $reqData['cprRegNmCn'] = $store_name;
                    $reqData['registCode'] = $store->store_license_no;
                    $reqData['businessLicStt'] = $store->store_license_stime ? date('Ymd', strtotime($store->store_license_stime)) : "";
                    $reqData['businessLicEnt'] = ($store->store_license_time == '长期') ? '29991231' : date('Ymd', strtotime($store->store_license_time));

                    //资料
                    $LicensePhoto = $storePayWaysController->vbill_uploadIMG($upload_request_url, '13', $LicensePhoto, $config_id, '营业执照照片');
                    if ($LicensePhoto['status'] == 0) {
                        $send_ways_data['status_desc'] = $LicensePhoto['message'];
                        $return = $storePayWaysController->send_ways_data($send_ways_data);
                        return $return;
                    }

                    //营业执照
                    $reqData['licensePic'] = $LicensePhoto['PhotoUrl'];
                    $reqData_img['licensePic'] = $LicensePhoto['PhotoUrl'];
                }

                $url = $obj->open_store_url;
                $VbillStore = VbillStore::query()->where('store_id', $store->store_id)->first();
                if ($VbillStore && $VbillStore->taskStatus > 1) {
                    $reqData['mno'] = $VbillStore->mno;
                    $url = $obj->open_update_store_url;
                    //入驻图片驳回
                    if ($VbillStore->taskStatus == 3) {
                        $reqData = $reqData_img;
                        $reqData['mno'] = $VbillStore->mno;
                    }
                }
                $data = [
                    'orgId' => $orgId,
                    'reqId' => time(),
                    'version' => '1.0',
                    'timestamp' => date('Ymdhis', time()),
                    'signType' => 'RSA',
                    'reqData' => $reqData,
                ];

                $data = array_filter($data, function ($v) {
                    if ($v == "") {
                        return false;
                    } else {
                        return true;
                    }
                });
                $re = $obj->execute($data, $url, $privateKey, $sxfpublic);
                Log::channel("income")->info(self::class."_income_result",[
                    "url"=>$url,
                    "req"=>$data,
                    "res"=>$re
                ]);
                if ($re['status'] == 0) {
                    throw new \Exception($re['message']);
                }
                if ($re['data']['code'] == "0000" && $re['data']['respData']['bizCode'] == "0000") {
                    $status_desc = "审核中";
                    $status = 2;
                } else {
                    $status_desc = $re['data']['respData']['bizMsg'] ?? '审核失败';
                    $status = 3;
                }
            } catch (\Exception $e) {
                throw new \Exception("VBILLSDK:" . $e->getMessage() . ' | ' . $e->getLine() . ' | ' . $e->getFile());
            }

            $data_in = [
                'config_id' => $config_id,
                'mno' => $re['data']['respData']['mno'] ?? "",
                'store_id' => $store->store_id,
                'applicationId' => $re['data']['respData']['applicationId'] ?? "",
            ];
            Log::channel("income")->info(self::class."_income_data_in",$data_in);
            if ($VbillStore) {
                $VbillStore->update($data_in);
                $VbillStore->save();
            } else {
                VbillStore::create($data_in);
            }

            $data['store_id'] = $store->store_id;
            $data['rate'] = $rate;
            $data['status'] = $status;
            $data['status_desc'] = $status_desc;
            $data['company'] = 'vbill';
            $return = $storePayWaysController->send_ways_data($data);
            return $return;
        } catch (\Exception $exception) {
            throw new \Exception($exception->getMessage());
        }
    }


    public function time($time)
    {
        try {
            //去除中文
            $time = preg_replace('/([\x80-\xff]*)/i', '', $time);

            $is_date = strtotime($time) ? strtotime($time) : false;

            if ($is_date) {
                $time = date('Y-m-d', strtotime($time));
            }

            return $time;
        } catch (\Exception $ex) {
            Log::info($ex->getMessage() . ' | ' . $ex->getFile() . ' | ' . $ex->getFile());
        }

        return $time;
    }

    public function city_name($city_code)
    {
        $city_name = "";
        $data = ProvinceCity::where('area_code', $city_code)->first();
        if ($data) {
            $city_name = $data->area_name;
        }

        return $city_name;

    }


    public function check_results(array $data)
    {
        $store_id = $data["store_id"];//$request->get('store_id', '');
//        $company = "vbill";//$data["company"];//$request->get('company', '');
        $JdStoreItem = Db::table('vbill_stores')->where(['store_id' => $store_id])->first();
        if (empty($JdStoreItem)) {
            throw new \Exception("配置信息不存在");
        }
        $config = new VbillConfigController();
        $vbill_config = $config->vbill_config($JdStoreItem->config_id);

        $obj = new \App\Api\Controllers\Vbill\BaseController();
        $url = $obj->open_query_store_url;
        $data = [
            'orgId' => $vbill_config->orgId,
            'reqId' => time(),
            'version' => '1.0',
            'timestamp' => date('Ymdhis', time()),
            'signType' => 'RSA',
            'reqData' => [
                'applicationId' => $JdStoreItem->applicationId, // f76c284da5644575aabe94043ccb637d
            ],
        ];
        $res = $obj->execute($data, $url, $vbill_config->privateKey, $vbill_config->sxfpublic);
        $ret = [
            "mno" => ""
        ];
        $msg = '';

        if (isset($res['data']['respData']['taskStatus']) && $res['data']['respData']['taskStatus'] == "1") {
            $status = 1;
            $message = '入驻审核通过';
            Db::table('store_pay_ways')->where(['store_id' => $store_id, 'status' => 2])->update(['status' => 1, 'status_desc' => '开通成功']);
            $ret = [
                "mno" => $res["data"]["respData"]["mno"] ?? ""
            ];
        } else {
            $status = 2;
            if (isset($res['data']['respData']['suggestion']) && !empty($res['data']['respData']['suggestion'])) {
                $msg = $res['data']['respData']['suggestion'];
            }
            $message = '入审核驻失败';
        }

        return [$status, $message, $msg, $ret];
    }


    //随机码+识别码
    public function chCode(array $data)
    {
        $code_number = $data["code_number"];
        $search_code = $data["search_code"];
        //验证信息
        $incomingQr = IncomingQrs::query()->where("code_number", $code_number)->first();
        if (empty($incomingQr)) {
            throw new \Exception("二维码不存在");
        } else if ($incomingQr->search_code != $search_code) {
            throw new \Exception("识别码不正确");
        }
        return $incomingQr;
    }


//$wx_channel_appid = $request->get('wx_channel_appid', ''); //微信渠道号
//$xcx_channel_appid = $request->get('xcx_channel_appid', ''); //小程序渠道号
//$weixin_path = $request->get('weixin_path', '');
    public function setMno(string $store_id)
    {
        $VbillStore = VbillStore::where('store_id', $store_id)->first();
        $MerchantId = $VbillStore->mno;
        $config_id = $VbillStore->config_id;

        $config = new VbillConfigController();
        $vbill_config = $config->vbill_config($config_id);
        if (!$vbill_config) {
            throw new \Exception("随行付配置不存在请检查配置");
        }

        //查询状态
        if ($VbillStore && $VbillStore->applicationId) {
            $obj = new \App\Api\Controllers\Vbill\BaseController();
            $url = $obj->open_query_store_url;
            $data = [
                'orgId' => $vbill_config->orgId,
                'reqId' => time(),
                'version' => '1.0',
                'timestamp' => date('Ymdhis', time()),
                'signType' => 'RSA',
                'reqData' => [
                    'applicationId' => $VbillStore->applicationId,
                ],
            ];

            $open_query_store = $obj->execute($data, $url, $vbill_config->privateKey, $vbill_config->sxfpublic);
            if ($open_query_store['data']['code'] == "0000" && $open_query_store['data']['respData']['bizCode'] == "0000") {
                if (isset($open_query_store['data']['respData']['taskStatus'])) {
                    //审核失败
                    if ($open_query_store['data']['respData']['taskStatus'] == "2" || $open_query_store['data']['respData']['taskStatus'] == "3") {
                        $data_up = [
                            'status' => 3,
                            'status_desc' => $open_query_store['data']['respData']['suggestion'],
                        ];
                        StorePayWay::where('store_id', $store_id)
                            ->where('company', 'vbill')
                            ->update($data_up);

                        $in_data = [
                            'taskStatus' => $open_query_store['data']['respData']['taskStatus'],
                            'wx_channel_appid' => ""
                        ];
                        VbillStore::where('store_id', $store_id)->update($in_data);
                        throw new \Exception($open_query_store['data']['respData']['suggestion']);
                    }
                }
            }
        }

        //商户信息查询接口
        $obj = new \App\Api\Controllers\Vbill\BaseController();
        $url = $obj->store_query_info;
        $data = [
            'orgId' => $vbill_config->orgId,
            'reqId' => time(),
            'version' => '1.0',
            'timestamp' => date('Ymdhis', time()),
            'signType' => 'RSA',
            'reqData' => [
                'mno' => $MerchantId,
            ],
        ];

        $re = $obj->execute($data, $url, $vbill_config->privateKey, $vbill_config->sxfpublic);
        if ($re['data']['code'] == "0000" && $re['data']['respData']['bizCode'] != "0000") {
            throw new \Exception($re['data']['respData']['bizMsg']);
        }

        //读取商户的费率
        $StorePayWay = StorePayWay::where('company', "vbill")
            ->where('store_id', $store_id)
            ->select(["rate", "rate_a", "rate_c", "rate_e", "rate_f", "rate_f_top"])
            ->first();
        if ($StorePayWay) {
            $rate = $StorePayWay->rate;
        } else {
            throw new \Exception("商户通道费率未设置");
        }

        //门店不一致无法保存
//                    if ($re['data']['respData']['mecDisNm'] != $store_name) {
//                        return json_encode([
//                            'status' => 2,
//                            'message' => '门店名称不一致、无法保存'
//                        ]);
//                    }

        //费率不一致无法保存
        if ($re['data']['respData']['qrcodeList'][0]['rate'] != $rate) {
            throw new \Exception('费率设置不一致、无法保存-' . $re['data']['respData']['qrcodeList'][0]['rate']);
        }

        $childNo = "";
        foreach ($re['data']['respData']['repoInfo'] as $k => $v) {
            if ($v['childNoType'] == "WX") {
                $childNo = $v['childNo'];
            } else {
                continue;
            }
        }

        //报备微信授权目录
        $obj = new \App\Api\Controllers\Vbill\BaseController();
        $url = $obj->weixin_config;
        $data = [
            'orgId' => $vbill_config->orgId,
            'reqId' => time(),
            'version' => '1.0',
            'timestamp' => date('Ymdhis', time()),
            'signType' => 'RSA',
            'reqData' => [
                'mno' => $MerchantId,
                'subMchId' => $childNo,
                'type' => '03',
                'jsapiPath' => env('APP_URL') . '/api/vbill/weixin/'
            ]
        ];
        $abc = $obj->execute($data, $url, $vbill_config->privateKey, $vbill_config->sxfpublic);
//                    Log::info('随行付-强开-报备微信授权目录结果');
//                    Log::info($abc);

        $insert_data = [
            'store_id' => $store_id,
            'config_id' => $config_id,
            'mno' => $MerchantId,
            'wx_channel_appid' => ""
        ];

        if ($VbillStore) {
            if ($VbillStore->applicationId == "") {
                $insert_data['taskStatus'] = 1;
            }
        } else {
            $insert_data['taskStatus'] = 1;
        }

        if ($VbillStore) {
            VbillStore::where('store_id', $store_id)
                ->update($insert_data);
        } else {
            VbillStore::create($insert_data);
        }


        //默认支付通道未注册成功
        // $data['store_id'] = $store_id;
        // $data['rate'] = $rate;
        // $data['status'] = $pay_status;
        // $data['status_desc'] = $pay_status_desc;
        // $data['company'] = 'vbill';
        // $return = $this->send_ways_data($data);
        DB::table('store_pay_ways')->where('store_id', $store_id)->where('company', 'vbill')->update(array('status' => 1, 'status_desc' => '开通成功'));
        $return = ['status' => 1, 'message' => '修改成功'];

        return $return;
    }

}

